package com.runfast.common.web.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.runfast.common.utils.TokenUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class JwtAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(TokenUtil.TOKEN);

        boolean flag = false;
        try {
            JWT decode = JWT.decode(token);
            Claim claim = decode.getClaim(TokenUtil.USER_ID);
            Integer userId = claim.asInt();
//            RunfastCuserService cuserService = SpringUtils.getBean(RunfastCuserService.class);
//            RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);
//            if(cuser==null)return flag = false;
//            else flag = true;
            flag = true;

        } catch (Exception e) {
            throw e;
        }

        return flag || (!isLoginRequest(request, response) && isPermissive(mappedValue));
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {

        try {
            request.getServletContext().getRequestDispatcher(getSuccessUrl()).forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
        request.setAttribute(getFailureKeyAttribute(), ae);
    }
}
